package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/7/26 15:24
 * @Version 1.0
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public String createPay(Long orderId) {

        //  根据订单Id 查询到orderInfo
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  生成二维码的前提是当前订单处于未支付或未关闭状态!
        if ("PAID".equals(orderInfo.getOrderStatus()) || "CLOSED".equals(orderInfo.getOrderStatus())){
            return "当前订单已支付或已关闭";
        }
        //  利用支付宝支付。
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问 http://3h444s.natappfree.cc/api/payment/alipay/callback/notify
        //  内网穿透工具：http://n5nkak.natappfree.cc 内网穿透工具，没重新开启一次，这个地址会发生变化！
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        //同步跳转地址，仅支持http/https  http://api.gmall.com/api/payment/alipay/callback/return
        request.setReturnUrl(AlipayConfig.return_payment_url);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", 0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", orderInfo.getTradeBody());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //  获取当前时间，在当前时间基础上+10m
        //  判断过期时间与有效期做比较!
        Instant instant = LocalDateTime.now().plusMinutes(10).atZone(ZoneId.systemDefault()).toInstant();
        Date from = Date.from(instant);
        //  yyyy-MM-dd HH:mm:ss
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bizContent.put("time_expire", simpleDateFormat.format(from));
        /******可选参数******/
        //bizContent.put("time_expire", "2022-08-01 22:00:00"); -- 推荐使用！
        //bizContent.put("time_expire", "90m");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        //   返回字符串 from 表单
        return response.getBody();
    }

    @Override
    public Boolean refund(Long orderId) {
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  查询out_trade_no;
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);

        //  创建请求退款对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
//        bizContent.put("out_request_no", "HZ01RF001");

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            if ("Y".equals(response.getFundChange())){
                System.out.println("调用成功");

                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());

                //  修改交易记录状态. payment_status
                this.paymentService.updatePaymentStatus(orderInfo.getOutTradeNo(),paymentInfo);
                //  发送消息修改订单状态。
                this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_ORDER_CLOSED,MqConst.ROUTING_ORDER_CLOSED,orderId);
                return true;
            }else {
                return false;
            }
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean closePay(Long orderId) {
        //  获取订单对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if (null==orderInfo){
            return false;
        }
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  创建关闭交易对象
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        //  只在支付成功时，并且异步回调才会给 trade_no 赋值。
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            //  如果支付宝关闭成功-那么就必须要关闭交易记录与订单记录.
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    @Override
    public Boolean checkPayment(Long orderId) {
        //  获取订单对象
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if (null==orderInfo){
            return false;
        }
        //  AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
        //  创建查询交易对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        //  只在支付成功时，并且异步回调才会给 trade_no 赋值。
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toJSONString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            //            if ("TRADE_SUCCESS".equals(response.getTradeStatus())){
            //                //  交易支付成功.
            //            }else if ("WAIT_BUYER_PAY".equals(response.getTradeStatus())){
            //                //  等待卖家付款
            //            }else {
            //                //  交易关闭
            //            }
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

}
